package com.alimama.shiro;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.alimama.dao.ICustDao;
import com.alimama.entity.shop.Cust;

@Component
public class SecurityRealm extends AuthorizingRealm {

	public static final String SESSION_USER_KEY = "shopping-";

	@Resource
	ICustDao custDao;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 把token转换成User对象
		Cust userLogin = tokenToUser((UsernamePasswordToken) token);
		// 验证用户是否可以登录
		Cust dbCust = custDao.queryByCustMblOrCustEmail(userLogin.getCustMbl());
		Object principal = token.getPrincipal();
		if(null == dbCust) 
			return null;
		SecurityUtils.getSubject().getSession().setAttribute("username", userLogin.getCustMbl());
		return new SimpleAuthenticationInfo(principal, dbCust.getCustPwd(), userLogin.getCustMbl());
	}

	private Cust tokenToUser(UsernamePasswordToken authcToken) {
		Cust cust = new Cust();
		cust.setCustMbl(authcToken.getUsername());
		cust.setCustPwd(String.valueOf(authcToken.getPassword()));
		return cust;
	}
}
